package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.admin.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MerchantMapper merchantMapper;


    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * @param userLoginDTO
     * @return
     */
    @Override
    public Result<UserLoginVO> login(UserLoginDTO userLoginDTO) {
        String opernId = getOpernId(userLoginDTO.getCode());
        if (StringUtils.isBlank(opernId)){
            throw new BaseException("缺失openid");
        }
        User user = userMapper.selectByOpenid(opernId);
        if (Objects.isNull(user)){
            user = User.builder()
                    .openid(opernId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        Map<String,Object> claims =  new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey()
                , jwtProperties.getUserTtl(), claims);
        log.info("token{}",token);
        Merchant merchant = merchantMapper.selectById(1);
        //计费
        String shopLonLat = merchant.getLocation();

        String userLonLat = userLoginDTO.getLocation();

//        double distance = MapUtils.calculateDistance(shopLonLat, userLonLat);

        BigDecimal delivoryCost = MapUtils.getDelivoryCost(shopLonLat, userLonLat);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(opernId)
                .token(token)
                .shopName(merchant.getShopName())
                .shopAddress(merchant.getShopAddress())
                .shopTelephone(merchant.getShopTelephone())
                .deliveryFee(delivoryCost)
                .shopId(merchant.getId())
                .build();

        return Result.success(userLoginVO);
    }

    private String getOpernId(String code) {
        Map<String,String> params = new HashMap<>();
        params.put("appid",weChatProperties.getAppid());
        params.put("secret",weChatProperties.getSecret());
        params.put("js_code",code);
        params.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, params);
        Map map = JSON.parseObject(json, Map.class);
        return map.get("openid").toString();
    }
}
